package com.qf.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * 2019/11/6
 * Administrator
 * mybatis001
 * 面向对象面向君  不负代码不负卿
 */
public class SessionUtils {

    private ThreadLocal<SqlSession> threadSession=new ThreadLocal<SqlSession>();
    //获取session
    protected synchronized SqlSession getsession(){
        SqlSession sqlSession = threadSession.get();
        if(sqlSession==null){
            try {
                sqlSession= new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"))
                         .openSession();
            } catch (IOException e) {
                e.printStackTrace();
            }
            threadSession.set(sqlSession);
        }
        return sqlSession;
    }
    //关闭session
    protected void closesession(){
        SqlSession session = threadSession.get();
        if(session!=null){
            session.close();
            threadSession.set(null);
        }
    }

}
